import { Subscription } from 'rxjs';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { WorkflowPageService } from 'src/app/common/page-render/workflow-page-container/workflow-page.service';
import { BaseService, DataRegisterService } from 'src/app/services';
import { EventManagerService } from 'src/app/services/event-manager.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { UploadService } from 'src/app/services/upload.service';
import { EngineService } from '../../../services/engine.service';
import { BaseFieldComponent } from '../base-field/base-field.component';
import * as dayjs from 'dayjs';
import { OrganizationTree } from 'src/app/models';
import { PermitService } from 'src/app/services/permit.service';
import { DataRPermits } from 'src/app/models/dataRPermits';

@Component({
  selector: 'zepride-task-top-bar',
  templateUrl: './task-top-bar.component.html',
  styleUrls: ['./task-top-bar.component.less', '../field.common.less']
})
export class TaskTopBarComponent extends BaseFieldComponent implements OnInit, OnDestroy {

  flowNodeUpdateSub: Subscription;
  workflowUpdatedSub: Subscription;

  statusDisplay: string = '待完成';
  updateTime: string = '待提交';
  userDisplay: string;

  departmentNodes: OrganizationTree[] = [];
  employeeList: OrganizationTree[] = [];
  projectPermits: DataRPermits[];

  flowNodeObj;
  orgId: string;
  pageId: string;
  status: string;

  constructor(
    protected engineService: EngineService,
    protected baseSvr: BaseService,
    protected eventSvr: EventManagerService,
    protected orgSvr: OrganizationService,
    public uploadService: UploadService,
    protected msg: NzMessageService,
    private wSvr: WorkflowPageService,
    public permitSvr: PermitService,
    protected dataRegisterService: DataRegisterService
  ) {
    super(engineService, baseSvr, eventSvr, orgSvr, uploadService, msg, dataRegisterService);
    this.orgId = localStorage.getItem('orgid');
  }
  ngOnDestroy() {
    if (this.flowNodeUpdateSub) {
      this.flowNodeUpdateSub.unsubscribe();
    }
    if (this.workflowUpdatedSub) {
      this.workflowUpdatedSub.unsubscribe();
    }
  }

  ngOnInit() {
    this.flowNodeUpdateSub = this.wSvr.flowNodeUpdate.subscribe(data => {
      if (!data) {
        return;
      }
      this.pageId = data.flowNode.pages[0].id;

      this.statusDisplay = data.status == 'finish' ? '已完成' : '待完成';
      this.status = data.status;
      if (data.updateTime) {
        this.updateTime = dayjs(data.updateTime).format('YYYY-MM-DD HH:mm:ss');
      }

      if (data.executor) {
        this.userDisplay = data.executor.name;
      }

    });

    this.workflowUpdatedSub = this.wSvr.workflowUpdated.subscribe(async data => {
      if (!data) {
        return;
      }

      if (data.userIds && data.userIds.length > 0 && data.datarPermits) {
        const list = await this.getDepartmentAndEmployee(data.userIds, data.datarPermits);
        this.userDisplay = list.map(x => `${x.userNode.nodeName}(${x.departmentNode.nodeName})`).join(' | ');
      }

    });
  }

  async getDepartmentAndEmployee(userIds: string[], permits: DataRPermits[]) {
    this.departmentNodes = await this.orgSvr.getOrganizationTrees({
      objectName: 'Department'
    });

    this.employeeList = await this.orgSvr.getOrganizationTrees({ objectName: 'User' });

    let result: {
      userNode: OrganizationTree,
      departmentNode: OrganizationTree
    }[] = [];
    for (const userId of userIds) {
      const employeeNode = this.employeeList.find(x => x.objectId == userId);
      const department = this.departmentNodes.find(x => x.id == employeeNode.parentId);

      //判断是否有当前节点的权限
      const filterPermits = permits.filter(x => x.authObjectId == department.objectId && x.refObjectType == 'Page' && x.refObjectId == this.pageId);

      if (filterPermits && filterPermits.length > 0) {
        result.push({
          userNode: employeeNode,
          departmentNode: department
        });
      }

    }

    return result;
  }

}
